﻿using System;
using System.Globalization;
using System.Linq;
using MySql.Data.MySqlClient;
using System.Collections.ObjectModel;

namespace Reviewer.Data.Bases
{
    /// <summary>
    /// CRUS Repository base with alternate key
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="PrimaryKey">The type of the rimary key.</typeparam>
    /// <typeparam name="AltKey">The type of the lt key.</typeparam>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes"), CLSCompliant(false)]
    public abstract class RepositoryCrudAlternativeBase<T, TPrimaryKey, TAltKey> : RepositoryCrudBase<T, TPrimaryKey>
        where T : class
        where TPrimaryKey : struct
        where TAltKey : struct
    {
        /// <summary>
        /// Selects items by the alternate key.
        /// </summary>
        /// <param name="keyValue">The key value.</param>
        /// <returns><c>Collection</c> of T</returns>
        public virtual Collection<T> SelectByAlternateKey(TAltKey keyValue)
        {
            CrudColumnInfo keyColumn = this.Columns.Single(co => co.IsAlternateKey);

            using (MySqlCommand command = new MySqlCommand(
                String.Format(CultureInfo.InvariantCulture
                , "{0} WHERE {1} = @{1}"
                , this.SelectAllQuery()
                , keyColumn.Name)))
            {
                keyColumn.AddParameter(command, keyValue);

                return ExecuteReaderAndBuildList(command);
            }
        }

        public virtual void DeleteByAlternateKey(TAltKey keyValue)
        {
            CrudColumnInfo keyColumn = this.Columns.Single(co => co.IsAlternateKey);

            using (MySqlCommand command = new MySqlCommand(
                String.Format(CultureInfo.InvariantCulture
                , "DELETE FROM {0} WHERE {1} = @{1}"
                , this.TableName
                , keyColumn.Name)))
            {
                keyColumn.AddParameter(command, keyValue);

                ExecuteNonQuery(command);
            }
        }
    }

}
